# -*- coding: utf-8 -*-
# coding:utf-8
__author__ = 'lancelrq'

import json
import time
import random
import urllib
import hashlib
import urllib2
import logging
import const as Const
from dbManager import DBManager

logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s [%(threadName)s]%(levelname)s: %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename='/data/wejudge/analysis_service.log',
)


class Base(object):

    def __init__(self, module_name='SYSTEM'):
        # self._dbManager = DBManager()
        # self._conn = self.__dbManager.getConn()
        self._const = Const
        self.__module_name = module_name
        pass

    def wejudge_api_call(self, url, data=None):
        try:
            datasend = None
            if data is not None:
                datasend = urllib.urlencode(data)
            t, r, s = Base.__api_license()
            req = urllib2.Request(url + "?timestamp=%s&randstr=%s&signature=%s" % (t, r, s), datasend)
            resp = urllib2.urlopen(req)
            body = resp.read()
            data = json.loads(body)
            if data.get('flag', False):
                return data.get('data')
            else:
                self.log(u"接口调用出错：%s(API_ERROR)" % data.get('msg'), 'WEJUDGE_API_CALLING', logging.ERROR)
                return False
        except urllib2.HTTPError, ex:
            self.log(u"接口网络访问失败(NATWORK_ERROR)", 'WEJUDGE_API_CALLING', logging.ERROR)
            return False

    def log(self, msg, source=None, level=logging.INFO):
        """
        日志调用
        :param msg: 日志消息
        :param source: 日志来源
        :param level:
        :return:
        """
        if source is None:
            source = self.__module_name
        print "[%s]#%s# %s" % (source, time.strftime("%m-%d %H:%M:%S"), msg)
        logging.log(level, '[%s] %s' % (source, msg))

    @staticmethod
    def __api_license():
        """
        接口访问权限生成器
        :return:
        """
        timestamp = str(int(time.time()))
        randstr = str("".join(random.sample(['0', '1', '2', '3', '4','5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'], 6)))
        secert = [
            Const.DATA_CENTER_API_SECERT,               # 接口访问授权密钥
            timestamp,
            randstr
        ]
        secert.sort()       # 字典序
        secert = hashlib.sha256("".join(secert)).hexdigest()
        return timestamp, randstr, secert
